//ComparatorTest1.java
package com.ylaihui.comparable;

import java.util.Arrays;
import java.util.Comparator;

public class ComparatorTest1 {
    public static void main(String[] args) {
        Animal[] animals= new Animal[6];
        animals[0] = new Animal("yy",23);
        animals[1] = new Animal("ll",23);
        animals[2] = new Animal("aa",24);
        animals[3] = new Animal("aa",27);
        animals[4] = new Animal("ii",28);
        animals[5] = new Animal("hh",28);

        Arrays.sort(animals, new Comparator() {
            @Override
            // 按 age 从大到小排序，age相同，按name从大到小排序
            public int compare(Object o1, Object o2) {
                if(o1 instanceof Animal && o2 instanceof Animal){
                    Animal a1 = (Animal) o1;
                    Animal a2 = (Animal) o2;
                    if(a1.age == a2.age)
                        return -a1.name.compareTo(a2.name);
                    return -(a1.age - a2.age);
                }else
                    throw new RuntimeException("类型不一致，无法比较");
            }
        });
        System.out.println(Arrays.toString(animals));
    }
}
